<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>我的家谱</span>
        <el-button type="primary" @click="openDialog()">创建新家谱</el-button>
      </div>
    </template>

    <el-table :data="paginatedTrees" v-loading="loading" empty-text="您还没有家谱，快创建一个吧!" style="width: 100%">
      <el-table-column type="expand">
        <template #default="props">
          <div style="padding: 10px 20px;">
            <el-descriptions title="家谱详细信息" :column="2" border>
              <el-descriptions-item label="家谱ID">{{ props.row.familyId }}</el-descriptions-item>
              <el-descriptions-item label="创建者用户ID">{{ props.row.userId }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ formatDateTime(props.row.createTime) }}</el-descriptions-item>
              <el-descriptions-item label="最后更新时间">{{ formatDateTime(props.row.updateTime) }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="name" label="家谱名称" width="200" />
      <el-table-column prop="contentDesc" label="描述" />
      <el-table-column prop="createTime" label="创建时间" width="200">
          <template #default="scope">{{ formatDateTime(scope.row.createTime) }}</template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="200">
           <template #default="scope">{{ formatDateTime(scope.row.updateTime) }}</template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="viewFamilyTree(scope.row.familyId)">查看图谱</el-button>
          <el-button size="small" type="primary" @click="openDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.familyId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalItems"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <!-- 【修正】补全了对话框内的表单和按钮 -->
  <el-dialog v-model="dialogVisible" :title="form.familyId ? '编辑家谱' : '创建新家谱'" width="500px" @close="resetForm">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="80px">
        <el-form-item label="家谱名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入家谱名称" />
        </el-form-item>
        <el-form-item label="描述" prop="contentDesc">
            <el-input v-model="form.contentDesc" type="textarea" placeholder="请输入家谱的描述信息" />
        </el-form-item>
    </el-form>
    <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import { getFamilyTreeListApi, createFamilyTreeApi, deleteFamilyTreeApi, updateFamilyTreeApi } from '@/api/family';
import type { FamilyTree } from '@/types/api';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';

const router = useRouter();
const trees = ref<FamilyTree[]>([]);
const loading = ref(true);
const submitLoading = ref(false);

const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const form = reactive<Partial<FamilyTree>>({});

const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = computed(() => trees.value.length);

const paginatedTrees = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return trees.value.slice(start, end);
});

const rules: FormRules = {
  name: [{ required: true, message: '家谱名称不能为空', trigger: 'blur' }]
};

const formatDateTime = (dateTimeStr?: string) => {
    if (!dateTimeStr) return 'N/A';
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', { hour12: false }).replace(/\//g, '-');
};

//获取家谱列表
const fetchTrees = async () => {
  loading.value = true;
  try {
    trees.value = await getFamilyTreeListApi();
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  form.familyId = undefined;
  form.name = '';
  form.contentDesc = '';
  formRef.value?.clearValidate();
};

// 打开对话框
const openDialog = (tree?: FamilyTree) => {
  resetForm();
  if (tree) {
    Object.assign(form, tree);
  }
  dialogVisible.value = true;
};

//提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true;
      try {
        const apiData = { name: form.name || '', contentDesc: form.contentDesc || '' };
        if (form.familyId) {
          await updateFamilyTreeApi(form.familyId, apiData);
          ElMessage.success('更新成功');
        } else {
          await createFamilyTreeApi(apiData);
          ElMessage.success('创建成功');
        }
        dialogVisible.value = false;
        await fetchTrees();
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

// 补全了函数逻辑
const handleDelete = async (id: number) => {
  await ElMessageBox.confirm('确定要删除这个家谱吗？此操作不可恢复。', '警告', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    type: 'warning',
  });
  await deleteFamilyTreeApi(id);
  ElMessage.success('删除成功');
  await fetchTrees();
};

const viewFamilyTree = (id: number) => {
  router.push({ name: 'FamilyTree', params: { id: id.toString() } });
};


const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
};

//当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
};

onMounted(fetchTrees);
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
